/*
 * @Author: ZL
 * @Date:   2019/05/15
 * @Last Modified by:   ZL
 * @Last Modified time: $ $
 */
var vm = new Vue({
  el: '#portal',
  data: function () {
    var _that = this;
    var checkSame = function (rule, value, callback) {
      if (value === '') {
        callback(new Error('请再次输入密码'));
      } else if (value !== _that.editPasswordData.newPassword) {
        callback(new Error('两次输入密码不一致！'));
      } else {
        callback();
      }
    };
    var checkDiffer = function (rule, value, callback) {
      if (value === '') {
        callback(new Error('请输入密码'));
      } else if (value == _that.editPasswordData.oldPassword) {
        callback(new Error('新密码和原密码不能相同！'));
      } else {
        callback();
      }
    };
    var checkOldPass = function (rule, value, callback) {
      if (value === '') {
        callback(new Error('请输入原密码'));
      } else {
        request('opus-admin', {
          url: ctx+'opus/front/om/users/passwordCheckout',
          data: {oldPassword: value},
          type: 'get'
        }, function (data) {
          if(data.success){
            callback();
          }else {
            callback(new Error(data.message ? data.message : '原密码错误'));
          }
        })
      }
    };
    return {
      headerData: [], // 头部菜单所有data
      headerActive: 0,  // 头部菜单active状态
      curWidth: (document.documentElement.clientWidth || document.body.clientWidth),//当前屏幕宽度
      curHeight: (document.documentElement.clientHeight || document.body.clientHeight),//当前屏幕高度
      showMenuMore: false,  // 展示更多菜单默认隐藏
      menuCount: 1, // 头部菜单展示条数 menuCount+1
      loginName: '', // 用户登陆名
      userName: '', // 用户名
      userId: '',  // 用户id
      hideHeaderData: [], // 头部菜单展示data
      headerDataShow: [], // 头部菜单隐藏data
      showMoreItem: false, // 是否展示隐藏的头部菜单
      topOrgId: '',
      userSex: '',
      iframeUrl: '',
      editPasswordFlag: false, // 是否展示修改密码弹窗
      editPasswordData: {
        oldPassword:'',
        newPassword: '',
        newPasswordCheck: ''
      }, // 修改密码data
      newPasswordCheck: '', // 再次确认新密码
      editPasswordRule: {
        oldPassword: [
          { required: true, validator: checkOldPass, trigger: 'blur' },
        ],
        newPassword: [
          { validator: checkDiffer, required: true, trigger: 'blur' }
        ],
        newPasswordCheck: [
          { validator: checkSame, required: true,trigger: 'blur' }
        ]
      },  // 修改密码校验
    }
  },
  mounted: async function () {
    var _that = this;
    this.ctx = await this.getCtx();
    window.addEventListener("resize", function () {
      vm.curWidth = document.documentElement.clientWidth;
      vm.curHeight = document.documentElement.clientHeight;
      vm.setHeaderShow();
    });
    //在document挂载onlick事件
    document.addEventListener("click", this.displayMenuPopover)
    // 监听子页面的传递过来的数据
    if (window.addEventListener) {
      window.addEventListener('message', _that.onMessage, false);
    } else {
      if (window.attachEvent) {
        window.attachEvent("onmessage", _that.onMessage);
      }
    }
    _that.getUserIndo();
  },
  methods: {
    getCtx:function(){
      return new Promise(function(resolve, reject){
        var httpRequest = new XMLHttpRequest();
        httpRequest.open("GET", "/agcim-viewer-ui/getSystemEnv.public", false);
        httpRequest.setRequestHeader(
            "Authorization",
            "bearer " + localStorage.getItem("access_token")
        );
        httpRequest.onreadystatechange = () => {
          if (httpRequest.readyState == 4 && httpRequest.status == 200) {
            try {
              //更新配置
              let env = JSON.parse(JSON.parse(httpRequest.responseText).message);
              var regexp = new RegExp("(?<=://).*?(?=/)");
              var ip = "";
              if (document.referrer.match(regexp) != null) {
                ip = RegExp.$1;
              }
              if (env.outerKeywords.split(",").includes(ip)) {
                ctx = changeUrl(env.opusPortalRest, document.referrer);
                resolve(ctx);
              } else {
                if (!Boolean(env.ipFromBrowser)) {
                  ctx = env.opusPortalRest;
                  resolve(ctx);
                  console.log("更新配置接口信息");
                } else {
                  ctx = changeUrl(env.opusPortalRest, document.referrer);
                  resolve(ctx);
                  console.log("更新配置接口信息");
                }
              }
            } catch (error) {
              reject();
              console.log("无法解析配置文件，继续使用默认配置");
            }
          }

          function changeUrl(oldItem, newItem) {
            var regexp = new RegExp("(?<=://).*?(?=/)");
            if (newItem.match(regexp) != null) {
              var a = RegExp.$1;
            }
            if (oldItem.match(regexp) != null) {
              var b = RegExp.$1;
            } else {
              var b = oldItem;
            }
            var result = oldItem.replace(b, a);
            return result.toString();
          }
        };
        httpRequest.send();
      })
    },
    getUserIndo: function () { // 获取用户登陆信息
      var _that = this;
      request('opus-admin', {
        url: ctx+'opus/front/om/users/currOpusLoginUser',
        // url: '../../../../../static/agcloud/framework/ui-schemes/dark-blue/js/user_1.json',
        type: 'get',
      }, function (data) {
        if(data.success){
          _that.loginName = data.content.user.loginName;
          _that.userName = data.content.user.userName;
          _that.userId = data.content.user.userId;
          _that.topOrgId = data.content.currentOrgId
          _that.getHeaderData();
          _that.getUserAllInfo(data.content.user.loginName);
        }
      }, function (msg) {
        alertMsg('', '服务请求失败', '关闭', 'error', true);
      });
    },
    getUserAllInfo: function(loginName){ // 获取登录用户所有信息
      var _that = this;
      request('agx', {
        // url: '../../../../../static/agcloud/framework/ui-schemes/dark-blue/js/user_2.json',
        url: ctx + 'opus/front/om/users',
        type: 'get',
        data: {loginName: loginName}
      }, function (data) {
        if(data.success){
          _that.userEmail = data.content.userEmail;
          _that.userSex = data.content.userSex;
        }
      }, function (msg) {
        alertMsg('', '服务请求失败', '关闭', 'error', true);
      });
    },
    getHeaderData: function () { // 获取菜单数据
      var _that = this;
      var props = {
        isTree: 'true',
        netName: '前端网络入口',
        tmnId: '1',
        topOrgId: _that.topOrgId,
        userId: _that.userId
      };
      var _that = this;
      request('opus-admin', {
        url: ctx+'opus/front/om/users/user/'+_that.userId+'/allMenus',
        // url: '../../../../../static/agcloud/framework/ui-schemes/dark-blue/js/menu_2.json',
        type: 'get',
        data: props
      }, function (data) {
        if(data.content){
          _that.headerData = data.content;
          _that.headerData.map(function(item){
            if(!item.menuIconCss){
              item.bigImgPath = ctx + item.bigImgPath;
            }
          });
          _that.headerActive = 0;
          _that.iframeUrl = data.content[0].menuInnerUrl;
          _that.setHeaderShow();
        }
      }, function (msg) {
        alertMsg('', '服务请求失败', '关闭', 'error', true);
      });
    },
    setHeaderShow: function () {  // 设置头部可展示菜单长度
      var _that = this;
      var logoWidth = $('.protal-header .subsystem-logo').outerWidth(true);
      var topbarWidth = $('.user-info-topbar').outerWidth(true);
      var width = _that.curWidth - logoWidth - topbarWidth;
      if (_that.headerData !== null && _that.headerData.length > 0) {
        var  count = parseInt(width/120);
        if(count < _that.headerData.length && count>0){
          _that.showMenuMore = true;
          _that.menuCount = count - 1;
        }else if(count<0 || count==0) {
          _that.showMenuMore = true;
          _that.menuCount = -1;
        }else {
          _that.showMenuMore = false;
          _that.menuCount = _that.headerData.length;
        }
      } else {
        _that.showMenuMore = false;
        _that.menuCount = _that.headerData.length;
      }
      _that.initMenuCount(_that.headerData, _that.menuCount)
    },
    initMenuCount: function (eleLi, n) {  // 重置头部菜单
      this.headerDataShow=eleLi.slice(0,n+1);
      this.hideHeaderData = eleLi.slice(n+1)
    },
    headerChangeMenu: function (data, index,e) { // 头部菜单点击事件
      if(this.headerActive == index && this.headerActive != -1){
        $('#contentZframe')[0].src = data.menuInnerUrl;
      }else {
        this.headerActive = index;
        this.iframeUrl = data.menuInnerUrl;
        $('#contentZframe').show();
        $('#contentZframe').siblings('iframe').remove();
      }
    },
    logout: function (e) { // 退出登陆
      e.cancelBubble = true;
      var _that = this;
      confirmMsg('', '确定要退出登陆吗？', function () {
        request('opus-admin', {
          url: ctx+'opus/front/om/users/listLogoutUrl',
          type: 'get',
          data: {
            netName : '前端网络入口',
            orgId: _that.topOrgId,
            userId : _that.userId
          }
        }, function (data) {
          if(data.success){
            if(data.content.length>0){
              var w = window.open();
              data.content.map(function(e){
                w.location = e;
              });
            }
            setTimeout(function () {
              w.close();
              window.location.href = ctx+ 'logout';
            },100);
          }
        }, function (msg) {
          window.location.reload();
          // alertMsg('', '服务请求失败', '关闭', 'error', true);
        });
      })
    },
    editPasswordSubmit: function(){ // 修改密码
      var _that = this;
      _that.$refs['editPasswordData'].validate(function (valid) {
        if (valid) {
          var props = {
            newPassword: _that.editPasswordData.newPassword,
            oldPassword: _that.editPasswordData.oldPassword,
          };
          request('opus-admin', {
            url: ctx+'opus/front/om/users/password',
            data: props,
            type: 'post'
          }, function (data) {
            if(data.success){
              _that.$message({
                message: '密码修改成功',
                type: 'success'
              });
              _that.editPasswordFlag = false;
            }else {
              _that.$message({
                message: data.message ? data.message : '密码修改失败',
                type: 'error'
              });
            }
          },function(msg){
            _that.$message({
              message: msg.message ? msg.message : '密码修改失败',
              type: 'error'
            });
          })
        } else {
          alertMsg('', '请输入完整且正确的信息', '关闭', 'warning', true);
          return false;
        }
      });
    },
    clearDialogData: function(formName){ // 清空表单
      this.$refs[formName].resetFields();
    },
    onMessage:function (e) {
      var _that = this;
      var data = e.data;
      if(!data.vueDetected&&data.id!=undefined){
        data.menuInnerUrl = e.origin + data.menuInnerUrl;
        _that.addTab(e,data,'MENU_'+data.id,_that.leftMenuActive++);
      }
    },
    displayMenuPopover:function () { // 隐藏tab操作窗口
      this.showTabOpt = false;
    }
  }
});